<template>
  <div class="pagination">
    <button 
    :disabled="pageNo === 1"
     @click="$emit('changePageNo', pageNo-1)"
    >上一页</button>
    <button v-show="startEndPage.start > 1" @click="$emit('changePageNo', 1)">
      1
    </button>

    <button v-show="startEndPage.start > 2">···</button>

    <button
      v-for="item in startEndArr"
      :key="item"
      :class="{ active: pageNo === item }"
      @click="$emit('changePageNo', item)"
    >
      {{ item }}
    </button>

    <button v-show="startEndPage.end < totalPages - 1">···</button>
    <button 
    v-show="startEndPage.end < totalPages"
     @click="$emit('changePageNo', totalPages)"
    >{{ totalPages }}</button>
    <button 
     @click="$emit('changePageNo', pageNo+1)"
    :disabled="pageNo === totalPages">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  mounted() {
    // setTimeout(() => {
    //   console.log(this.startEndPage, "111");
    // }, 2000);
  },
  props: ["totalPages", "pageNo", "continuePage", "total"],
  computed: {
    //totalPages:总页数,pageNo:当前页,continuePage:连续页长度
    //根据传过来的数据计算连续页
    startEndPage() {
      const { totalPages, pageNo, continuePage } = this;
      //计算连续页开始和结束的数字
      let start = 0;
      let end = 0;
      //当总页数小于连续页长度,起始是1,结束是总页数
      if (totalPages < continuePage) {
        start = 1;
        end = totalPages;
      } else {
        //当总页数大于连续页长度根据pageNo设置start和end
        start = pageNo - Math.floor(continuePage / 2);
        end = pageNo + Math.floor(continuePage / 2);

        if (start < 1) {
          //如果start小于1了,直接设置起始值为1,end为continuePage
          start = 1;
          end = continuePage;
        }
        if (end > totalPages) {
          //如果end大于总页数了,设置end为总页数,起始值为end-continuePage+1
          end = totalPages;
          start = totalPages - continuePage + 1;
        }
      }
      return { start, end };
    },
    //设置一个数组,数组是当前应该呈现的页码
    startEndArr() {
      const arr = [];
      for (var i = this.startEndPage.start; i <= this.startEndPage.end; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
